<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="icon-upload" size="small" type="primary" @click=" dialogVisible=true">
      上传本地图片
    </el-button>
    <el-dialog v-model="dialogVisible">
      <el-upload
        action=""
        :http-request="Upload" 
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :limit="12"
        :on-remove="removeImage"
        :before-upload="beforeAvatarUpload"
        class="editor-slide-upload"
        list-type="picture-card"
        drag
      >
        <el-button type="primary" style="margin-top:80px;">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确定
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import { client, randomWord } from '@/utils/alioss'
import { ElMessage } from 'element-plus'
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: []
    }
  },
  methods: {
    handleSubmit() {
      this.$emit('successCBK', this.fileList)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response.data.url
          this.listObj[objKeyArr[i]].hasSuccess = true
          return
        }
      }
    },
    Upload(file){
      var fileName = `img/${randomWord(true, 20)}${+new Date()}${file.file.name.substr(file.file.name.indexOf('.'))}`
      client().put(fileName, file.file).then(result => {
        console.log(result)
        this.fileList.push({
          url: result.url,
          uid: file.file.uid,
          saveUrl: 'https://img.qumoyugo.com/' + result.name,
        })
      }).catch(err => {
        console.log(err)
      })
    },
    removeImage(file){
      const index = this.fileList.findIndex(item => {
        return item.uid == file.uid
      })
      this.fileList.splice(index, 1)
    },
    beforeAvatarUpload(file){
      const isLt2M = file.size / 1024 < 200
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过200kb!')
      }
      return isLt2M
    },
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  :deep(.el-upload--picture-card) {
    width: 100%;
    height: 180px;
  }
  :deep(.el-upload-dragger) {
    width: 100%;
    background: transparent;
  }
}
</style>
